package com.example.shirodemo.demos.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    private static final long expire = 3600 * 1000;
    private static final String securit= "!@#$%H*&^SxJ";

    /**
     * 生成token
     */
    public static String toToken(String iss, String sub, String jti, Map<String, String> claims) {
        JWTCreator.Builder builder = JWT.create();
        // 设置头部
        Map<String, Object> headers = new HashMap<>();
        headers.put("alg", "HS256");
        headers.put("typ", "JWT");
        builder.withHeader(headers);
        // 设置载荷
        // 默认字段
        builder.withIssuer(iss);  // 发行者
        builder.withSubject(sub); // 主题
        builder.withJWTId(jti);   // token唯一表示（使用sessionId）
       builder.withIssuedAt(new Date()); // 发行时间
        builder.withExpiresAt(new Date(new Date().getTime() + expire));
        // 自定义字段
        claims.forEach(builder::withClaim);
        // 签名，生成token
        return builder.sign(Algorithm.HMAC256(securit));
    }

    /**
     * 验签
     */
    public static boolean parseToken(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(securit)).build();
        try {
            jwtVerifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 解析数据
     */
    public static DecodedJWT parseData(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(securit)).build();
        return jwtVerifier.verify(token);
    }
}
